package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductService;

import java.io.*;
import java.net.Socket;
import java.util.*;

public class EStoreClient {

    // 服务器地址和端口（与Server保持一致）
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;

    // 购物车：key是商品ID，value是购买数量
    private Map<String, Integer> shoppingCart = new HashMap<>();

    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        // 程序启动时加载购物车数据
        loadCartData();

        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    showSortedProducts();
                    break;
                case 5:
                    saveCartData();
                    System.out.println("感谢使用，再见！");
                    return;
                case 99:
                    backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    public static void backupData() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            // 1. 创建字节输入流和输出流，分别指向源文件和目标备份文件
            fis = new FileInputStream("products.dat");
            fos = new FileOutputStream("products.dat.bei");

            // 2. 创建缓冲区字节数组
            byte[] buffer = new byte[1024];
            int len; // 用于存储每次读取的字节数

            // 3. 循环读取并写入数据
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            System.out.println("数据备份成功！");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("数据备份失败：" + e.getMessage());
        } finally {
            // 4. 关闭流资源
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void showMenu() {
        System.out.println("\n 欢迎来到商城 ");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 自定义排序浏览商品");
        System.out.println("5. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void browseProducts(Comparator<Product> comparator) {
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            // 1. 连接服务器
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            System.out.println("已连接到服务器");

            // 2. 获取输入输出流
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());

            // 3. 发送请求（与Server约定的字符串）
            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();
            System.out.println("已发送请求：GET_ALL_PRODUCTS");

            // 4. 接收服务器响应
            Object response = ois.readObject();//等待服务器响应
            if (response instanceof List<?>) {
                List<Product> products = (List<Product>) response;

                // 如果有排序要求，则对商品列表进行排序
                if (comparator != null) {
                    products.sort(comparator);
                }

                System.out.println("\n===== 商品列表 =====");
                for (Product product : products) {
                    System.out.println(product); // 需确保Product重写了toString()
                }
            } else {
                System.out.println("无效的响应格式");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("连接服务器失败: " + e.getMessage());
        } finally {
            // 5. 关闭资源
            try {
                if (ois != null) ois.close();
                if (oos != null) oos.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    /**
     * 通过Socket连接服务器查找特定商品
     * @param productId 商品ID
     * @return 商品对象，如果找不到返回null
     */
    private Product findProductById(String productId) {
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            // 1. 连接服务器
            socket = new Socket(SERVER_HOST, SERVER_PORT);

            // 2. 获取输入输出流
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());

            // 3. 发送查找商品的请求
            oos.writeObject("FIND_PRODUCT_BY_ID");
            oos.writeObject(productId);
            oos.flush();

            // 4. 接收服务器响应
            Object response = ois.readObject();
            if (response instanceof Product) {
                return (Product) response;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭资源
            try {
                if (ois != null) ois.close();
                if (oos != null) oos.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }


    private void showSortedProducts() {
        System.out.println("\n 请选择具体的排序方式： ");
        System.out.println("1. 按照id升序");
        System.out.println("2. 按照价格升序");
        System.out.println("3. 按照价格降序");
        System.out.println("4. 按照库存数量降序");
        System.out.print("请输入您的选择: ");
        int choice = scanner.nextInt();
        Comparator<Product> comparator = null;
        switch (choice){
            case 1:
                comparator = Comparator.comparing(Product::getId);
                break;
            case 2:
                comparator = Comparator.comparingDouble(Product::getPrice);
                break;
            case 3:
                comparator = Comparator.comparingDouble(Product::getPrice).reversed();
                break;
            case 4:
                comparator = Comparator.comparingInt(Product::getStock).reversed();
            default:
                System.out.println("无效的选项，请重新输入！");
        }
        browseProducts(comparator);
    }

    /**
     * 保存购物车数据到文件
     */
    private void saveCartData() {
        ProductService.saveData(shoppingCart);
    }

    /**
     * 从文件加载购物车数据
     */
    private void loadCartData() {
        shoppingCart = ProductService.loadData();
        if (!shoppingCart.isEmpty()) {
            System.out.println("购物车数据加载完成，共 " + shoppingCart.size() + " 种商品");
        }
    }


    public static void main(String[] args) {
        new EStoreClient().start();
    }
}